﻿using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.UnitedNationsNews.Framework;
using Microsoft.Devices;
using Microsoft.Phone.Net.NetworkInformation;
using Environment = Microsoft.Devices.Environment;

namespace JustinAngel.Neurons.Framework
{
    public class NetworkStatusProvider : INetworkStatusProvider
    {
        public NetworkStatusProvider()
        {
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            IoC.Get<IMessenger>().Send(new IsConnectChangedMessage(IsConnected));
        }

        public bool IsConnected
        {
            get
            {
                if (Environment.DeviceType == DeviceType.Emulator)
                    return true;

                
                return Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
            }
        }

        public bool IsConnectedToZune
        {
            get
            {
                if (Environment.DeviceType == DeviceType.Emulator)
                    return false;


                if (Debugger.IsAttached)
                    return false;

#if DEBUG
                return false; 
#endif


                return Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet;
            }
        }

        public bool IsConnectedToWifi
        {
            get {  return Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
                || Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet;
            }
        }
    }

    public class IsConnectChangedMessage : GenericMessage<bool>
    {
        public IsConnectChangedMessage(bool content) : base(content)
        {
        }

        public IsConnectChangedMessage(object sender, bool content) : base(sender, content)
        {
        }

        public IsConnectChangedMessage(object sender, object target, bool content) : base(sender, target, content)
        {
        }
    }
}